﻿using bilibili下载.Interface;
using HttpHelper;
using Newtonsoft.Json;
using NLog;
using System.Collections;
using System.Collections.Generic;

namespace bilibili下载.Models
{
    public class BVAnalysis : IAnalysis
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();
        private AVAnalysis VInfos { get; }

        public BVAnalysis(string BvId)
        {
            VInfos = new AVAnalysis(GetAvid(BvId));
        }

        private string GetAvid(string BvId)
        {
            WinHttp http = new WinHttp();
            var query = new Dictionary<string, string>
            {
                ["bvid"] = BvId
            };
            logger.Debug("开始获取BvId：{0}", BvId);
            http.Open(Method.GET, "https://api.bilibili.com/x/web-interface/view", query);
            var data = http.Send();
            if (data.IsSuccessStatus)
            {
                logger.Debug("BvId：{0},内容：{1}", BvId, data.Text);
                var result = JsonConvert.DeserializeObject<BvResponse>(data.Text);
                if (result.code == 0)
                {
                    return result?.data?.aid;
                }
                else logger.Debug("BvId：{0},解析失败", BvId);
            }
            else logger.Debug("BvId：{0},获取失败.状态码：{1}.状态信息：{2}.错误描述：{3}", BvId, data.StatusCode, data.Status, data.Message);
            return string.Empty;
        }

        public IEnumerator<IAVInfo> GetEnumerator()
        {
            return VInfos.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return VInfos.GetEnumerator();
        }

        private class BvResponse
        {
            public int code { get; set; }
            public string message { get; set; }
            public BvData data { get; set; }
        }

        private class BvData
        {
            public string bvid { get; set; }
            public string aid { get; set; }
        }
    }
}